package com.cl.security.system.service;

import com.cl.security.common.result.CommonResult;
import com.cl.security.system.entity.Menu;
import com.cl.security.system.entity.User;
import com.cl.security.system.repository.MenuRepository;
import com.cl.security.system.repository.UserRepository;
import com.cl.security.base.service.TreeService;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class MenuService extends TreeService<Menu,MenuRepository> {
    private final MenuRepository menuRepository;
    private final UserRepository userRepository;

    protected MenuService(MenuRepository menuRepository, MenuRepository menuRepository1, UserRepository userRepository) {
        super(menuRepository);
        this.menuRepository = menuRepository1;
        this.userRepository = userRepository;
    }
    public CommonResult getByType(Long id, Integer type) {
        User user = userRepository.findById(id).get();
        Set<Menu> menuSet = new LinkedHashSet<>();
        user.getRoles().forEach(role -> {
            menuSet.addAll(role.getMenus().stream()
                    .filter(menu -> menu.getParent() == null && menu.getType() == type)
                    .collect(Collectors.toSet()));
        });
        Set<Menu> sortedMenus = menuSet.stream().sorted(Comparator.comparing(Menu::getSort))
                .collect(Collectors.toCollection(LinkedHashSet::new));
        return CommonResult.success(sortedMenus);
    }
}
